package com.leetcode.No0817;

import org.junit.Test;

import java.util.HashSet;
import java.util.Objects;

/**
 * @program: leetcode
 * @description: 链表组件
 * @author: wangzhihua
 * @date: 2022-10-12
 *
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
public class Solution {
	public int numComponents(ListNode head, int[] nums) {
		HashSet<Integer> numSet = new HashSet<>();
		for (int num : nums) {
			numSet.add(num);
		}

		int ans = 0;
		ListNode curNode = head;
		while (Objects.nonNull(curNode)) {
			int tempAns = 0;
			while (Objects.nonNull(curNode) && numSet.contains(curNode.val)) {
				++tempAns;
				curNode = curNode.next;
			}
			ans += tempAns > 0 ? 1 : 0;

			if (Objects.nonNull(curNode)) {
				curNode = curNode.next;
			}
		}

		return ans;
	}

	@Test
	public void test1() {
		ListNode listNode = new ListNode(0, new ListNode(1, new ListNode(2)));
		int[] nums = new int[]{0, 2};
		System.out.println(this.numComponents(listNode, nums));
	}

	public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) {
		  this.val = val;
	  }
      ListNode(int val, ListNode next) {
		  this.val = val;
		  this.next = next;
	  }
  }
}
